﻿using System;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using mojoPortal.Web.RS.SBM.AppCode.Lib;

namespace mojoPortal.Web.RS.SBM.Controls
{
    public partial class IssueControl : RSBaseUserControl
    {
        
        protected void Page_Load(object sender, EventArgs e)
        {
            
            if (Request.QueryString["action"] == "edit" || Request.QueryString["action"] == "add")
            {
                btnEditIssue.Visible = false;
                btnSaveIssue.Visible = true;
            }

        }
        public void SetControlEnabledState(bool bstate = false)
        {
            
            RSSBMCommonFunctions.SetControlsEnabledState(this, bstate);
        }
        public bool LoadIssueDataByID(int companyid, int WorkOrderid, int Issueid)
        {
            bool bHaveData = false;

            if (companyid > 0)
            {
                RSSBMDataLookupLoader.LoadAssignToCHK(companyid, chkAssignTo);
                RSSBMDataLookupLoader.LoadStatusDDL(companyid, "ISSUE_CAT", ddlIssueStatus);

                if (WorkOrderid > 0)
                {
                    int locationid = 0;
                    txtWorkOrderId.Text = WorkOrderid.ToString();
                    
                    if (Issueid > 0)
                    {
                        string strSQL = "SELECT i.IssueId, i.IssueName, i.Description, i.Response, i.IssueDT, i.CloseDT,";
                        strSQL = strSQL + " i.WorkOrderId, i.AssignTo, i.LocationId, i.StatusId, i.CompanyId";
                        strSQL = strSQL + " FROM rs_tblIssue i WHERE i.workorderid=@WorkOrderId AND i.IssueId=@IssueId";
                        strSQL = strSQL + " AND i.CompanyId=@CompanyId ORDER BY i.IssueDT DESC";

                        SqlCommand myCommand;
                        SqlParameter param;
                        SqlConnection myConnection;
                        myConnection = new SqlConnection(ConfigurationManager.ConnectionStrings[GetRSCompanyConnectionString()].ToString());
                        myCommand = new SqlCommand(strSQL, myConnection);
                        SqlDataReader myDataReader;

                        param = new SqlParameter();
                        param.SqlDbType = SqlDbType.Int;
                        param.ParameterName = "@Companyid";
                        param.Value = companyid;
                        myCommand.Parameters.Add(param);

                        param = new SqlParameter();
                        param.SqlDbType = SqlDbType.Int;
                        param.ParameterName = "@WorkOrderid";
                        param.Value = WorkOrderid;
                        myCommand.Parameters.Add(param);

                        param = new SqlParameter();
                        param.SqlDbType = SqlDbType.Int;
                        param.ParameterName = "@Issueid";
                        param.Value = Issueid;
                        myCommand.Parameters.Add(param);

                        myConnection.Open();
                        myDataReader = myCommand.ExecuteReader(CommandBehavior.CloseConnection);
                        if (myDataReader.HasRows)
                        {
                            myDataReader.Read();
                            locationid = int.Parse(myDataReader["LocationId"].ToString());
                            ucLocationHeaderControl.LoadLocationHeader(companyid, locationid);

                            txtIssueId.Text = Issueid.ToString();
                            txtWorkOrderId.Text = myDataReader["workorderid"].ToString();
                            txtIssueName.Text = myDataReader["IssueName"].ToString();

                            if (myDataReader["IssueDT"] != DBNull.Value)
                            {
                                DateTime issuedt = Convert.ToDateTime(myDataReader["IssueDT"].ToString());
                                txtIssueTime.Text = issuedt.ToShortTimeString();
                                txtIssueDate.Text = issuedt.ToShortDateString();
                            }

                            if (myDataReader["CloseDT"] != DBNull.Value)
                            {
                                DateTime closedt = Convert.ToDateTime(myDataReader["CloseDT"].ToString());
                                txtCloseTime.Text = closedt.ToShortTimeString();
                                txtCloseDate.Text = closedt.ToShortDateString();
                            }

                            txtDescription.Text = myDataReader["Description"].ToString();
                            txtResponse.Text = myDataReader["Response"].ToString();
                            if (myDataReader["StatusId"] != DBNull.Value)
                                ddlIssueStatus.SelectedValue = myDataReader["StatusId"].ToString();

                            RSSBMCommonFunctions.SetMultiSelectList(myDataReader["AssignTo"].ToString(), chkAssignTo);
                            bHaveData = true;

                            if (Request.QueryString["action"] == "edit")
                            {  
                                btnDeleteIssue.Visible = true;
                            }
                            else
                            {
                                SetControlEnabledState(false);
                            }
                        }

                        myConnection.Close();
                    }
                    locationid = RSSBMCommonFunctions.GetLocationIDByWorkOrderID(companyid, WorkOrderid);
                    ucLocationHeaderControl.LoadLocationHeader(companyid, locationid);
                }
            }
            return bHaveData;
        }
        
        ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

        protected void btnSaveIssue_Click(object sender, EventArgs e)
        {
            RSUserIdentity userIdentity = GetRSUserIdentity();
            int CompanyId = userIdentity.RSCompanyId;

            int LocationId = ucLocationHeaderControl.LocationId;
            int WorkOrderId = txtWorkOrderId.Text == "" ? 0 : Convert.ToInt32(txtWorkOrderId.Text);
            int IssueId = txtIssueId.Text == "" ? 0 : Convert.ToInt32(txtIssueId.Text);

            string IssueName = txtIssueName.Text.Trim();
            string IssueDT = txtIssueDate.Text + " " + txtIssueTime.Text.Trim();
            string CloseDT = txtCloseDate.Text + " " + txtCloseTime.Text.Trim();
            IssueDT = IssueDT.Trim();
            CloseDT = CloseDT.Trim();
            string Description = txtDescription.Text.Trim();
            string Response = txtResponse.Text.Trim();

            string AssignTo = RSSBMCommonFunctions.GetMultiSelectValue(chkAssignTo);
            int StatusID = Convert.ToInt32(ddlIssueStatus.SelectedValue);

            SqlCommand sqlCmd = new SqlCommand();

            SQLHelper.AddParamToSQLCmd(sqlCmd, "@ReturnValue", SqlDbType.Int, 0, ParameterDirection.ReturnValue, null);
            SQLHelper.AddParamToSQLCmd(sqlCmd, "@IssueName", SqlDbType.NVarChar, 100, ParameterDirection.Input, IssueName);
            SQLHelper.AddParamToSQLCmd(sqlCmd, "@Description", SqlDbType.NVarChar, -1, ParameterDirection.Input, Description);
            SQLHelper.AddParamToSQLCmd(sqlCmd, "@Response", SqlDbType.NVarChar, -1, ParameterDirection.Input, Response);
            SQLHelper.AddParamToSQLCmd(sqlCmd, "@IssueDT", SqlDbType.NVarChar, 15, ParameterDirection.Input, IssueDT);
            
            if(CloseDT.Length > 0)
                SQLHelper.AddParamToSQLCmd(sqlCmd, "@CloseDT", SqlDbType.NVarChar, 15, ParameterDirection.Input, CloseDT);

            SQLHelper.AddParamToSQLCmd(sqlCmd, "@IssueID", SqlDbType.Int, 0, ParameterDirection.Input, IssueId);
            SQLHelper.AddParamToSQLCmd(sqlCmd, "@AssignTo", SqlDbType.NVarChar, 100, ParameterDirection.Input, AssignTo);
            SQLHelper.AddParamToSQLCmd(sqlCmd, "@StatusId", SqlDbType.Int, 0, ParameterDirection.Input, StatusID);
            SQLHelper.AddParamToSQLCmd(sqlCmd, "@WorkOrderId", SqlDbType.Int, 0, ParameterDirection.Input, WorkOrderId);
            SQLHelper.AddParamToSQLCmd(sqlCmd, "@LocationId", SqlDbType.Int, 0, ParameterDirection.Input, LocationId);
            SQLHelper.AddParamToSQLCmd(sqlCmd, "@CompanyId", SqlDbType.Int, 0, ParameterDirection.Input, CompanyId);
            SQLHelper.AddParamToSQLCmd(sqlCmd, "@CurrentUser", SqlDbType.NVarChar, 25, ParameterDirection.Input, userIdentity.RSCurrentUser);
            SQLHelper.SetCommandType(sqlCmd, CommandType.StoredProcedure, "rs_uspSaveIssue");
            SQLHelper.ExecuteScalarCmd(sqlCmd);

            int returnValue = Convert.ToInt32(sqlCmd.Parameters["@ReturnValue"].Value);
            string prevurl = string.Empty;
            if (Session["PreviousURL"] != null)
                prevurl = Session["PreviousURL"].ToString();
            else
                prevurl = Request.UrlReferrer.ToString();

            ucModalActionMessageControl.ShowModal("Issue Successfully Saved!", prevurl, true);
        }
        protected void btnDeleteIssue_Click(object sender, EventArgs e)
        {
            RSUserIdentity userIdentity = GetRSUserIdentity();
            if (userIdentity.RSCanWrite && userIdentity.RSCanDelete)
            {
                int companyid = userIdentity.RSCompanyId;
                int WorkOrderid = Convert.ToInt32(txtWorkOrderId.Text);
                int issueid = Convert.ToInt32(txtIssueId.Text);
                RemoveWorkOrderIssue(companyid, WorkOrderid, issueid);
            }
            else
                ucModalActionMessageControl.ShowModal("You Do Not Have Permission To Perform This Action!", "", false);
        }
        private void RemoveWorkOrderIssue(int companyid, int WorkOrderid, int issueid)
        {
            if (companyid > 0 && WorkOrderid > 0 && issueid > 0)
            {
                SqlCommand sqlCmd = new SqlCommand();
                SQLHelper.AddParamToSQLCmd(sqlCmd, "@ReturnValue", SqlDbType.Int, 0, ParameterDirection.ReturnValue, null);
                SQLHelper.AddParamToSQLCmd(sqlCmd, "@WorkOrderid", SqlDbType.Int, 0, ParameterDirection.Input, WorkOrderid);
                SQLHelper.AddParamToSQLCmd(sqlCmd, "@issueid", SqlDbType.Int, 0, ParameterDirection.Input, issueid);
                SQLHelper.AddParamToSQLCmd(sqlCmd, "@companyid", SqlDbType.Int, 0, ParameterDirection.Input, companyid);
                SQLHelper.SetCommandType(sqlCmd, CommandType.Text, "DELETE FROM rs_tblIssue WHERE issueid=@issueid AND workorderid=@WorkOrderid AND companyid=@companyid");
                SQLHelper.ExecuteScalarCmd(sqlCmd);
                int returnValue = Convert.ToInt32(sqlCmd.Parameters["@ReturnValue"].Value);
                Response.Redirect(Request.RawUrl);
            }
        }
        protected void btnReturn_Click(object sender, EventArgs e)
        {
            Response.Redirect("~/RS/SBM/RSWorkOrderIssues.aspx?workorderid=" + txtWorkOrderId.Text);
        }
        protected void btnEditIssue_Click(Object sender, EventArgs e)
        {
            RSUserIdentity userIdentity = GetRSUserIdentity();
            if (userIdentity.RSCanWrite)
            {
                Response.Redirect(Request.Url.ToString() + "&action=edit");
                //SetControlEnabledState(true);
                //btnEditIssue.Visible = false;
                //btnSaveIssue.Visible = true;
                //btnDeleteIssue.Visible = true;
            }
            else
                ucModalActionMessageControl.ShowModal("You Do Not Have Permission To Perform This Action!", "", false);
        }
       

    }

    
}